//
//  Camera.m
//  CIRectangleDetectDemo
//
//  Created by fujikoli(李鑫) on 2017/8/29.
//  Copyright © 2017年 fujikoli(李鑫). All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Camera.h"

@implementation Camera

-(void)actionWithBufferDelegate:(nullable id<AVCaptureVideoDataOutputSampleBufferDelegate>)delegate previewLayerFrame:(CGRect)frame{
    [self setCaptureSession:[[AVCaptureSession alloc] init]];
    _captureSession.sessionPreset = AVCaptureSessionPresetHigh;
    [self addVideoInputFromCamera];
    [self addVideoOutput];
    dispatch_queue_t queue = dispatch_queue_create("RectangleVideoQueue", DISPATCH_QUEUE_SERIAL);
    [self.output setSampleBufferDelegate:delegate queue:queue];
    [self addVideoPreviewLayer];
    [self addPhotoOutput];
    self.previewLayer.frame = frame;
    //加入拍摄防抖，可提高检测质量
    [self cameraBackgroundDidClickOpenAntiShake];
}

- (void)addVideoPreviewLayer
{
    [self setPreviewLayer:[[AVCaptureVideoPreviewLayer alloc] initWithSession:[self captureSession]]];
    [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
}

- (void)addVideoInputFromCamera
{
    AVCaptureDeviceDiscoverySession *deviceDiscoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionBack];
    for (AVCaptureDevice *device in deviceDiscoverySession.devices) {
        if ([device position] == AVCaptureDevicePositionBack) {
            self.device = device;
            break;
        }
    }
    
    NSError *error = nil;
    AVCaptureDeviceInput *backFacingCameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if (!error)
    {
        if ([_captureSession canAddInput:backFacingCameraDeviceInput])
        {
            [_captureSession addInput:backFacingCameraDeviceInput];
        }
    }
}

- (void)addVideoOutput{
    [self setOutput:[[AVCaptureVideoDataOutput alloc]init]];
    [_output setAlwaysDiscardsLateVideoFrames:YES];
    [_output setVideoSettings:@{(id)kCVPixelBufferPixelFormatTypeKey:@(kCVPixelFormatType_32BGRA)}];
    if([_captureSession canAddOutput:_output]){
        [_captureSession addOutput:_output];
    }
}

-(void)addPhotoOutput{
    [self setImageOutput:[[AVCapturePhotoOutput alloc]init]];
    if([_captureSession canAddOutput:_imageOutput]){
        [_captureSession addOutput:_imageOutput];
    }
}

///聚焦
-(void)focusAt:(CGSize)size point:(CGPoint)point{
    CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
    NSError *error;
    if ([self.device lockForConfiguration:&error]) {
        if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            [self.device setFocusPointOfInterest:focusPoint];
            [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
        }
        [self.device unlockForConfiguration];
    }
}
///开始扫描
-(BOOL)startRunning{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        [self.captureSession startRunning];
        return YES;
    }
    return NO;
}
///停止扫描
-(void)captureStopRunning{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        [self.captureSession stopRunning];
    }
}
-(void)takePictureWith:(id<AVCapturePhotoCaptureDelegate>)delegate{
    AVCapturePhotoSettings *settings = [AVCapturePhotoSettings photoSettingsWithFormat:@{AVVideoCodecKey:AVVideoCodecJPEG}];
    [self.imageOutput capturePhotoWithSettings:settings delegate:delegate];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self captureStopRunning];
    });
}
///防抖开启
- (void)cameraBackgroundDidClickOpenAntiShake {
    AVCaptureConnection *captureConnection = [self.output connectionWithMediaType:AVMediaTypeVideo];
    AVCaptureDevice *videoDevice = self.device;
    NSLog(@"set format: %@", videoDevice.activeFormat);
    if ([videoDevice.activeFormat isVideoStabilizationModeSupported:AVCaptureVideoStabilizationModeCinematic]) {
        captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeCinematic;
    }
}
///防抖关闭
- (void)cameraBackgroundDidClickCloseAntiShake {
    AVCaptureConnection *captureConnection = [self.output connectionWithMediaType:AVMediaTypeVideo];
    NSLog(@"change captureConnection: %@", captureConnection);
    AVCaptureDevice *videoDevice = self.device;
    if ([videoDevice.activeFormat isVideoStabilizationModeSupported:AVCaptureVideoStabilizationModeOff]) {
        captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeOff;
    }
}

- (void)dealloc {
    [[self captureSession] stopRunning];
    _previewLayer = nil;
    _captureSession = nil;
    _stillImage = nil;
    _output = nil;
}

@end
